package com.focus.xyz.core.utils;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.StringUtils;
import org.openqa.selenium.By;

import java.io.InputStream;

/**
 * Created by cimon on 2016/3/23.
 */
public class ObjectMap {
    private PropertiesConfiguration properties;
    private String filePrefix = "selenium/";
    private String fileSuffix = ".properties";


    //页面元素分别在不同的properties文件中配置，允许有多个objectMap实例
    public ObjectMap(String propFile){
        properties = new PropertiesConfiguration();
        try{
            properties.load(loadInputStreamFromClassPath(filePrefix + propFile +fileSuffix));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static InputStream loadInputStreamFromClassPath(String file_path) throws Exception {
        return Thread.currentThread().getContextClassLoader().getResourceAsStream(file_path);
    }

    public By getLocator(String element) throws Exception{
        String locator = (String) properties.getProperty(element);
        if(StringUtils.isBlank(locator)){
            throw new Exception("读取元素配置项失败");
        }
        String[] l = locator.split(">");
        if(l==null||l.length==0){
            throw new Exception("元素配置项错误");
        }
        String locatorType = l[0];
        String locatorValue = l[1];
        locatorValue = new String( locatorValue.getBytes("ISO-8859-1"),"UTF-8");
        if("id".equalsIgnoreCase(locatorType)){
            return By.id(locatorValue);
        }else if("name".equalsIgnoreCase(locatorType)){
            return By.name(locatorValue);
        }else if("classname".equalsIgnoreCase(locatorType)||"class".equalsIgnoreCase(locatorType)){
            return By.className(locatorValue);
        }else if("tag".equalsIgnoreCase(locatorType)||"tagname".equalsIgnoreCase(locatorType)){
            return By.tagName(locatorValue);
        }else if("link".equalsIgnoreCase(locatorType)||"linktext".equalsIgnoreCase(locatorType)){
            return By.linkText(locatorValue);
        }else if("partiallinktext".equalsIgnoreCase(locatorValue)){
            return By.partialLinkText(locatorValue);
        }else if("cssselector".equalsIgnoreCase(locatorType)){
            return By.cssSelector(locatorValue);
        }else if("xpath".equalsIgnoreCase(locatorType)){
            return By.cssSelector(locatorValue);
        }else{
            throw new Exception("未知的locatorType:"+locatorType);
        }
    }
}
